<template>
  <div class="app-container">
    <!-- 表单 -->
    <div style="width: 70%; margin-left: 15%;">
      <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="getPositioning">定位
      </el-button>
      <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white" @click="isStart = true">
        选择起点
      </el-button>
      <el-button slot="prepend" style="width: 120px; background: #cc3333; color: white" @click="isStart = false">
        选择终点
      </el-button>
      <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="getRoute()" v-show="hidden">获取路径
      </el-button>
    </div>
    <!-- 搜索组件 -->
    <div>
      搜索目的地：
      <el-select
          v-model="keywords"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
          :clearable="true"
          size="mini"
          @change="currentSelect"
          style="width: 500px"
      >
        <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item"
            class="one-text"
        >
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.district }}</span>
        </el-option>
      </el-select>
    </div>
    <!-- 地图组件 -->
    <div id="guide-map" style="height: 500px;"></div>
    <!-- 轨迹回放控制 -->
    <div class="input-card">
      <h4>轨迹回放控制</h4>
      <div class="input-item">
        <el-button class="btn" type="primary" @click="startAnimation">开始动画</el-button>
        <el-button class="btn" type="primary" @click="pauseAnimation">暂停动画</el-button>
      </div>
      <div class="input-item">
        <el-button class="btn" type="primary" @click="resumeAnimation">继续动画</el-button>
        <el-button class="btn" type="primary" @click="stopAnimation">停止动画</el-button>
      </div>
    </div>
    <!--    行程信息-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>
        尊敬的用户您好!<br>
        您的行程信息如下:<br>
        起始地为:{{ addressStartIndo }}<br>
        终点地为:{{ addressEndIndo }}<br>
        预计行程里程为:{{ routeInfo.mileage }}公里,<br>
        预计行程时间:{{ routeInfo.time }}分钟,<br>
        预计金额:{{ routeInfo.price }}元!<br>
        请按实际金额支付!<br>
      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import {getAddressByLocation, getRoute} from "@/api/amap/amap";
import {queryDriverList} from "@/api/driver/driver";

window._AMapSecurityConfig = {
  securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe',
}
export default {
  components: {},
  mounted() {
    this.initMap();
  },
  data() {
    return {
      // 提交表单
      form: {},
      // 地图实例
      map: null,
      // 路径坐标点集合
      coordinateList: [],
      // 起点坐标
      startCoordinate: {},
      // 终点坐标
      endCoordinate: {},
      // 选择起点
      isStart: true,
      // 起点Marker
      startMarker: null,
      // 终点Marker
      endMarker: null,
      // 搜索点Marker
      searchMarker: null,
      // 搜索提示
      AutoComplete: null,
      //起始地
      addressStartIndo: '',
      // 终点地
      addressEndIndo: '',
      // 搜索关键字
      keywords: "",
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      // 轨迹回放相关
      marker: null,
      lineArr: [
        [121.697057, 30.872076],
      ],
      passedPolyline: null,
      RouteReq: {
        origin: '',
        destination: ""
      },
      hidden: false,
      dialogVisible: false,
      routeInfo: {
        mileage: "",
        time: "",
        price: ""
      },
      driver:{}
    };
  },
  methods: {
    // 初始化地图
    initMap() {
      AMapLoader.reset();
      AMapLoader.load({
        key: 'd104a14bc704385633a52121150da15d',
        version: '2.0',
        plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Marker', 'AMap.Polyline', 'AMap.MoveAnimation'],
        AMapUI: {
          version: '1.1',
          plugins: []
        },
        securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe', // 将安全码提前放置在 AMapLoader 的配置中
      }).then((AMap) => {
        // 初始化地图
        this.map = new AMap.Map('guide-map', {
          viewMode: "2D",
          zoom: 13,
          center: [121.697216, 30.869781],
          resizeEnable: true,
          willreadoften: true
        });
        this.startMarker = new AMap.Marker({
          position: new AMap.LngLat(121.697216, 30.869781),
          title: '起点',
          label: {content: '起点'}
        });
        this.RouteReq.origin = "121.697216, 30.869781"
        this.getStartAddress(this.RouteReq.origin)
        // 将创建的点标记添加到已有的地图实例
        this.map.add(this.startMarker);
        // 鼠标点击事件
        this.map.on('click', this.clickMapHandler);
        // 搜索提示插件
        AMap.plugin('AMap.AutoComplete', () => {
          this.AutoComplete = new AMap.AutoComplete({city: "上海"});
        });
        // 初始化司机分布
        this.getDriver(AMap)
      }).catch(e => {
        console.log(e);
      });
    },
    //获取起点名
    getStartAddress(location) {
      getAddressByLocation(location).then(res => {
        this.addressStartIndo = res.data.regeocode.formattedAddress
      })
    },
    //获取终点名
    getEndAddress(location) {
      getAddressByLocation(location).then(res => {
        this.addressEndIndo = res.data.regeocode.formattedAddress
      })
    },
    // 点击地图事件
    clickMapHandler(e) {
      // 选择起点
      if (this.isStart) {
        if (this.startMarker !== null) {
          this.map.remove(this.startMarker);
        }
        this.startCoordinate.lon = e.lnglat.getLng();
        this.startCoordinate.lat = e.lnglat.getLat();
        // 标点
        this.startMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
          title: '起点',
          label: {content: '起点'}
        });
        // 将创建的点标记添加到已有的地图实例
        this.map.add(this.startMarker);
        this.lineArr.push(this.startMarker.lon, this.startMarker.lat)
        this.RouteReq.origin = this.startCoordinate.lon + ',' + this.startCoordinate.lat
        this.getStartAddress(this.RouteReq.origin)
        console.log("起点经度为:" + this.startCoordinate.lon + ',     纬度：' + this.startCoordinate.lat);
      }
      // 选择终点
      else {
        if (this.endMarker !== null) {
          this.map.remove(this.endMarker);
        }
        this.endCoordinate.lon = e.lnglat.getLng();
        this.endCoordinate.lat = e.lnglat.getLat();
        this.endMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
          title: '终点',
          label: {content: '终点'}
        });
        this.map.add(this.endMarker);
        console.log("终点经度为:" + this.endCoordinate.lon + ',     纬度：' + this.endCoordinate.lat);
        this.RouteReq.destination = this.endCoordinate.lon + ',' + this.endCoordinate.lat
        this.getEndAddress(this.RouteReq.destination)
        if (this.RouteReq.destination != null && this.RouteReq.origin != null && this.RouteReq.origin != undefined && this.RouteReq.destination != undefined) {
          this.hidden = true
        }
      }
    },
    // 搜索地址
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(query, (status, result) => {
            this.options = result.tips;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 选中提示
    currentSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      // 清除marker
      if (this.searchMarker) {
        this.map.remove(this.searchMarker);
      }
      // 设置marker
      this.searchMarker = new AMap.Marker({
        map: this.map,
        position: [val.location.lng, val.location.lat]
      });
      this.keywords = val.name;
      // 定位
      this.map.setCenter([val.location.lng, val.location.lat]);
      this.RouteReq.destination = val.location.lng + ',' + val.location.lat
      console.log(this.keywords + "经度为:" + val.location.lng + ",纬度为:" + val.location.lat);
    },
    getRoute() {
      getRoute(this.RouteReq).then(res => {
        let polylineArr = [];
        for (let i = 0; i < res.data.route.paths[0].steps.length; i++) {
          let coordinates = [];
          let polyline = res.data.route.paths[0].steps[i].polyline.split(';');
          for (let j = 0; j < polyline.length; j++) {
            let [lng, lat] = polyline[j].split(',');
            coordinates.push([parseFloat(lng), parseFloat(lat)]);
          }
          polylineArr.push(coordinates);
        }
        const formattedPolylines = polylineArr.flat().map(coord => [coord[0], coord[1]]);
        this.lineArr = []
        this.lineArr.push(...formattedPolylines);
        const data={
          type: 5,
          params: {
            userName: "admin",
            OrderTrajectory: this.lineArr,
          },
        }
        this.$parent.sendPositioning(data)
        //计算距离
        this.routeInfo.mileage = (res.data.route.paths[0].distance) / 1000
        //计算时间
        this.routeInfo.time = (res.data.route.paths[0].duration) / 60
        //计算价格
        this.routeInfo.price = res.data.route.taxi_cost
        this.dialogVisible = true
        AMapLoader.load({
          key: 'd104a14bc704385633a52121150da15d',
          version: '2.0',
          plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Marker', 'AMap.Polyline', 'AMap.MoveAnimation'],
          AMapUI: {
            version: '1.1',
            plugins: []
          },
          securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe', // 将安全码提前放置在 AMapLoader 的配置中
        }).then((AMap) => {
          this.initAnimation(AMap);
        }).catch(e => {
          console.log(e);
        });
      })
    },
    initAnimation(AMap) {
      // 清空上一次的轨迹
      if (this.marker) {
        this.marker.setMap(null);
      }
      if (this.polyline) {
        this.polyline.setMap(null);
      }
      if (this.passedPolyline) {
        this.passedPolyline.setMap(null);
      }

      // 绘制新的轨迹
      this.marker = new AMap.Marker({
        map: this.map,
        position: this.lineArr[0],
        icon: "https://webapi.amap.com/images/car.png",
        offset: new AMap.Pixel(-13, -30),
        autoRotation: true,
        angle: -90
      });

      this.polyline = new AMap.Polyline({
        map: this.map,
        path: this.lineArr,
        showDir: true,
        strokeColor: "#28F",
        strokeWeight: 6
      });
      this.passedPolyline = new AMap.Polyline({
        map: this.map,
        strokeColor: "#AF5",
        strokeWeight: 6
      });
      this.marker.on('moving', (e) => {
        this.passedPolyline.setPath(e.passedPath);
      });
      this.map.setFitView();
    },
    //定位
    getPositioning() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            position => {
              const latitude = position.coords.latitude;
              const longitude = position.coords.longitude;
              this.positioning = longitude + ',' + latitude;
              // 使用获取到的经纬度进行其他操作
            },
            error => {
              console.error('获取位置失败:', error.message);
            }
        );
      } else {
        console.error('浏览器不支持地理位置服务');
      }
    },
    // 开始动画
    startAnimation() {
      this.marker.moveAlong(this.lineArr, 200);
    },
    // 暂停动画
    pauseAnimation() {
      this.marker.pauseMove();
    },
    // 继续动画
    resumeAnimation() {
      this.marker.resumeMove();
    },
    // 停止动画
    stopAnimation() {
      this.marker.stopMove();
    },
    //动态实施路径
    updateTrack(coordinates) {
      // 如果地图尚未初始化，则初始化地图
      if (!this.map) {
        this.initMap();
      }
      AMapLoader.load({
        key: 'd104a14bc704385633a52121150da15d',
        version: '2.0',
        plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Marker', 'AMap.Polyline', 'AMap.MoveAnimation'],
        AMapUI: {
          version: '1.1',
          plugins: []
        },
        securityJsCode: '6e9af3bb840ac51b7cad8594dcf79cbe',
      }).then((AMap) => {
        // 移动地图视角到最新位置
        this.map.setCenter(coordinates);
        // 如果司机标记已经存在，则移动标记到新位置
        if (this.driverMarker) {
          this.driverMarker.setPosition(coordinates);
        } else {
          // 否则，创建新的司机标记
          this.driverMarker = new AMap.Marker({
            position: coordinates,
            map: this.map,
            icon: "https://webapi.amap.com/images/car.png",
          });
        }
      }).catch(e => {
        console.log(e);
      });
    },
    getDriver(AMap) {
      queryDriverList().then(res => {
        if (res.data.length > 0) {
          res.data.forEach(item => {
            const marker = new AMap.Marker({
              map: this.map,
              position: [item.driverLongitude, item.driverLatitude],
              icon: "https://webapi.amap.com/images/car.png",
              offset: new AMap.Pixel(-13, -30),
              autoRotation: true,
              angle: -90
            });

            // 使用箭头函数和 Vue 的 bind 方法
            const handleClick = () => {
              const infoWindow = new AMap.InfoWindow({
                content: `
              <div>
                <p>司机姓名：${item.driverName}</p>
                <p>司机简介：${item.driverIntro}</p>
                <p>司机状态：
                  ${item.driverState === 1 ? '未上线' : ''}
                  ${item.driverState === 2 ? '挂起' : ''}
                  ${item.driverState === 3 ? '接单中' : ''}
                  ${item.driverState === 4 ? '空闲' : ''}
                </p>
                <!-- 添加其他司机信息字段 -->
              </div>
            `,
                position: marker.getPosition(),
                offset: new AMap.Pixel(0, -30),
              });

              infoWindow.open(this.map);
            };

            // 添加点击事件监听器
            marker.on('click', handleClick.bind(this));
          });
        }
      });
    }
  },
  created() {
  },
};
</script>

